import React from "react";
import { Form, Input, Button } from "antd-mobile";
import useDown from "../../Hooks/useDown";
import { getCodeApi, getLoginApi } from "../../api/users";
import { useNavigate } from "react-router-dom";

function Index() {
  let nav=useNavigate()
  const [fn, flag, num] = useDown();
  const [form] = Form.useForm();
  const yzm = async () => {
    const val = form.getFieldValue("tel");
    const reg = /^1\d{10}$/;
    if (reg.test(val)) {
      fn();
      const result = await getCodeApi(val);
      console.log(result);
      form.setFieldValue("telCode", result.data.data.telCode);
    }
  };
  const onsubmit = async () => {
    try {
      const result = await form.validateFields();
      const info = await getLoginApi(result);
      console.log(info);
      localStorage.setItem("token", info.data.data.token);
      console.log('ok');
      nav('/')

    } catch {
      console.log("no");
    }
   
  };
  return (
    <div>
      <Form
        form={form}
        layout="horizontal"
        mode="card"
        footer={
          <Button
            block
            type="submit"
            color="primary"
            size="large"
            onClick={onsubmit}
          >
            登录
          </Button>
        }
      >
        <Form.Item
          label="手机号"
          name="tel"
          rules={[
            { required: true, message: "手机号不能为空" },
            {
              pattern: /^1\d{10}$/,
              message: "手机号格式错误",
            },
          ]}
        >
          <Input placeholder="请输入手机号" />
        </Form.Item>
        <Form.Item
          label="短信验证码"
          name="telCode"
          extra={
            <Button disabled={flag} onClick={yzm}>
              {flag ? `${num}发送验证码` : "发送验证码"}
            </Button>
          }
        >
          <Input placeholder="请输入验证码" />
        </Form.Item>
      </Form>
    </div>
  );
}

export default Index;
